package com.tensquare.manager.filter;

import cn.hutool.core.util.StrUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.sql.Struct;

/**
 * Created by WF on 2020/10/28 10:21
 * 后端的网关过滤器
 */
@Component
public class ManagerFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    //执行业务逻辑
    @Override
    public Object run() throws ZuulException {
        //1.)得到请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        //2.)放行一些资源
        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        if(request.getRequestURL().toString().contains("/login")){
            return  null;
        }

        //3.)得到请求头，如果请求头中有需要token信息，就添加此请求头到zuul的请求头中
        String header = request.getHeader("Authorization");
        if(StrUtil.isNotBlank(header) && header.startsWith("Bearer ")){
            //3.1)从第7位开始截取，得到token
            String token = header.substring(7);
            //3.2)解析token
            Claims claims = jwtUtil.parseJWT(token);
            //3.3)判断是否有值，如果有值，就得到roles的值，判断是否为admin,如果是就添加请求头到zuul的请求头中
            if(claims != null){
                String roles = (String) claims.get("roles");
                if(StrUtil.isNotBlank(roles) && "admin".equals(roles)){
                    currentContext.addZuulRequestHeader("Authorization",header);
                    return null;
                }
            }
        }

        //4.)其它情况，不允许访问，对请求进行拦截
        currentContext.setSendZuulResponse(false);      //关闭响应
        currentContext.setResponseStatusCode(403);      //设置响应的状态码
        currentContext.setResponseBody("无权访问！");     //设置响应体的内容
        currentContext.getResponse().setContentType("text/html;charset=utf-8");  //设置响应体的内容类型
        return null;
    }
}
